using System;
using System.Collections.Generic;
using System.Xml.XPath;
using Eclipse.TRCore.Http;

namespace Eclipse.TRCore.Travians.Actions
{
    public class GetLoginPageAction : TravianAction<GetLoginPageInput, GetLoginPageResult>
    {
        private XPathExpression XPATH_FORM = XPathExpression.Compile("//form[1]/@action");
        private XPathExpression XPATH_INPUTS = XPathExpression.Compile("//form[1]//input");

        public override void DoAction()
        {
            IEClient client = new IEClient();
            this.ActionResult.RawHtml = client.GetResponseString(this.Input.LoginUrl);
            LoginAction nextAction = this.NextAction as LoginAction;
            
            XPathNodeIterator iterator;
            XPathNavigator nav;
            nav = GetSgmlDOM(this.ActionResult.RawHtml);
            iterator = nav.Select(XPATH_FORM);
            if(iterator.Count > 0)
            {
                iterator.MoveNext();
                this.ActionResult.TagetResult.PostUrl = new Uri(IEClient.GetUri(this.Input.LoginUrl, null), iterator.Current.Value);;
            }
            else 
                goto Error;

            iterator = nav.Select(XPATH_INPUTS);
            if (iterator.Count > 0)
            {
                foreach (XPathNavigator navigator in iterator)
                {
                    navigator.MoveToAttribute("name", "");
                    string name = navigator.Value;
                    navigator.MoveToParent();
                    navigator.MoveToAttribute("value", "");
                    string value = navigator.Value;
                    this.ActionResult.TagetResult.LoginArguments.Add(name, value);
                }
            }
            else 
                goto Error;



            //if(null != nextAction)
            //{
            //    nextAction.Input.PostLoginUrl = @"s2.travian.cn/dorf1.php";
            //    nextAction.Input.HttpPostArguments.Add("w", "1024:768");
            //    nextAction.Input.HttpPostArguments.Add("login", "1182836087");
            //    nextAction.Input.HttpPostArguments.Add("e057ee1", "");
            //    nextAction.Input.HttpPostArguments.Add("e69403e", "");
            //    nextAction.Input.HttpPostArguments.Add("e5454fa", "d0c413a4e9");
            //    nextAction.Input.HttpPostArguments.Add("autologin", "ja");
            //    nextAction.Input.HttpPostArguments.Add("s1.x", "38");
            //    nextAction.Input.HttpPostArguments.Add("s1.y", "9");
            //}

            Error:
            {
                
            }
        }
    }
    public class GetLoginPageInput
    {
        public string LoginUrl;

    }

    public class GetLoginPageResult
    {
        public IDictionary<string, string> LoginArguments = new Dictionary<string, string>();
        public Uri PostUrl;

    }

}
